package de.dhbw.karlsruhe.picsim.util.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.swing.*;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * Created by IntelliJ IDEA.
 * User: user
 * Date: May 1, 2010
 * Time: 10:28:57 PM
 */

/**
 * Hängt
 */
public final class LoggingExceptionHandler implements Thread.UncaughtExceptionHandler {
    private static final Log log = LogFactory.getLog(LoggingExceptionHandler.class);

    @Override
    public void uncaughtException(final Thread t, final Throwable e) {
        log.error("uncaught Exception in " + t, e);
        showErrorWindow(e);
    }

    static void showErrorWindow(final Throwable e) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                final JDialog dialog = new JDialog();
                dialog.setTitle("Fehler Aufgetreten");

                dialog.setVisible(true);
                final JPanel contentPane = new JPanel();
                dialog.setContentPane(contentPane);
                final StringWriter writer = new StringWriter();
                e.printStackTrace(new PrintWriter(writer));
                contentPane.add(new JTextArea(writer.toString()));
                dialog.pack();
            }
        });
    }
}
